package com.spc.car.service.sys.impl;

import com.spc.car.data.entity.sys.SysRole;
import com.spc.car.data.entity.sys.SysRoleMenu;
import com.spc.car.data.service.sys.SysRoleDeptService;
import com.spc.car.data.service.sys.SysRoleMenuService;
import com.spc.car.data.service.sys.SysRoleService;
import com.spc.car.data.service.sys.SysUserRoleService;
import com.spc.car.service.domain.po.sys.RolePO;
import com.spc.car.service.sys.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysRoleDeptService sysRoleDeptService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    @Transactional
    public boolean save(@NotNull RolePO rolePO) {
        SysRole  sysRole = new SysRole();
        BeanUtils.copyProperties(rolePO, sysRole);

        boolean result = sysRoleService.saveOrUpdate(sysRole);

        if (null != rolePO.getRoleId()) {
          sysRoleMenuService.deleteRoleMenuByRoleId(rolePO.getRoleId());
        }

        if (CollectionUtils.isNotEmpty(rolePO.getMenuIds())) {
            List<SysRoleMenu> roleMenus = new ArrayList<>();
            rolePO.getMenuIds().forEach(menuId -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setRoleId(sysRole.getRoleId());
                roleMenus.add(sysRoleMenu);
            });
            result = sysRoleMenuService.saveBatch(roleMenus);
        }
        return result;
    }

}
